<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}角色`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="drawerProps.row.roleName" clearable></el-input>
      </el-form-item>

      <el-form-item label="权限字符" prop="roleKey">
        <el-input v-model="drawerProps.row.roleKey" clearable></el-input>
      </el-form-item>

      <el-form-item label="角色顺序" prop="roleSort">
        <el-input-number v-model="drawerProps.row.roleSort"></el-input-number>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="drawerProps.row.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="drawerProps.row.remark"></el-input>
      </el-form-item>

      <el-form-item label="菜单权限" prop="menuIds">
        <el-tree
          ref="menuTreeRef"
          v-model="drawerProps.row.menuIds"
          :data="menuList"
          :props="menuTreeSelectProps"
          node-key="menuId"
          show-checkbox
          :default-checked-keys="drawerProps.row.menuIds"
        >
        </el-tree>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="RoleDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance, ElTree } from "element-plus";
import { Menu } from "@/api/interface/systemMenu";
import { Role } from "@/api/interface/systemRole";
import { getMenuListApi } from "@/api/modules/menu";
import { getRoleDetailApi } from "@/api/modules/role";
import { menuTreeHandle } from "@/utils/index";

const menuTreeSelectProps = {
  label: "menuName"
};

const rules = reactive({
  roleName: [{ required: true, message: "请填写角色名称" }],
  roleKey: [{ required: true, message: "请填写权限字符" }],
  roleSort: [{ required: true, message: "请填写角色顺序" }]
});

// 树形角色
const menuList = ref<Menu.MenuListRes[]>([]);

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Role.RoleDetailRes>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  menuId?: number;
  parentId?: number;
  roleId?: number;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 获取菜单列表
const getMenuList = async () => {
  return getMenuListApi().then(res => {
    const { data } = res;
    if (data.length > 0) {
      menuList.value = menuTreeHandle(data, data[0].parentId);
    } else {
      menuList.value = [];
    }
  });
};

// 获取角色详情
const getRoleDetail = async (roleId: number) => {
  const { data } = await getRoleDetailApi(roleId);
  drawerProps.value.row = data;
};

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;

  // 获取菜单列表
  await getMenuList();

  drawerProps.value.row.status = 1;
  drawerProps.value.row.roleSort = 1;

  // 获取角色详情
  if (undefined != params.roleId && params.roleId > 0) {
    await getRoleDetail(params.roleId);
  }

  drawerVisible.value = true;
};

const menuTreeRef = ref<InstanceType<typeof ElTree>>();

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      // 获取选中的菜单列表
      const menuIds: number[] = menuTreeRef.value!.getCheckedKeys() as number[];
      drawerProps.value.row.menuIds = menuIds;

      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}角色成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
<style scoped>
.el-icon-inline-block {
  display: inline-block;
}
</style>
